//
//  CrowdVoiceItemViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/25.
//

import Foundation
import LeanCloud
//制作音色
class CrowdVoiceItemViewModel : BaseViewModel {
    
    func doVoice(bean: AiVoiceCrowdBean) {
        if AudioPlayerManager.shared.isPlaying() {
            showToast("正在播放中，请稍后")
            return
        }
        request {
            let text = configManager.getConfig().aiChat.aiVoiceTestStr
            let (hexString, hexData) = try await AiChatExt.doAiVoiceTest(text: text, voiceId: bean.voiceId, voiceHex: bean.voiceHex)
            if ((bean.voiceHex ?? "").isEmpty) {
                bean.voiceHex = hexString
                //保存数据
                try await LeancloudManager.instance.save(todo: bean)
            }
            try check(hexData != nil, "播放失败")
            return hexData!
        } suc: {
            AudioPlayerManager.shared.playData(from: $0)
        } fail: {
            showTipsDialog(text: $0.message) {}
        }
        
    }
    
    //检查音色是否存在
    func checkVoiceExit(bean: AiVoiceCrowdBean, suc: @escaping () -> Void) {
        
        request {
            try check(userManager.isLogin(), "请先登陆")
            //查询是否已经存在了，避免重复添加
            let query = LCQuery(className: "AiVoice")
            query.whereKey("crowdId", .equalTo(bean.objectId ?? ""))
            query.whereKey("voiceId", .equalTo(bean.voiceId ?? ""))
            query.whereKey("userId", .equalTo(userManager.getUserId()))
            let voiceBean = try await LeancloudManager.instance.getFirst(query: query, modeType: AiVoiceBean.self)
            try check(voiceBean == nil, "已经存在了，无法重复添加")
            return true
        } suc: { _ in
            suc()
        } fail: {
            showLog($0.message)
            showTipsDialog(text: $0.message) {}
        }
        
    }
    
    func doBuy(bean: AiVoiceCrowdBean, deduct:Bool = false) {
        
        request {
            try check(userManager.isLogin(), "请先登陆")
            //开始添加
            let voiceBean = AiVoiceBean()
            voiceBean.crowdId = bean.objectId
            voiceBean.name = bean.name
            voiceBean.userId = userManager.getUserId()
            voiceBean.voiceHex = bean.voiceHex
            voiceBean.voiceId = bean.voiceId
            voiceBean.status = 1
            try await  retry(maxRetries: 5, retryDelayMillis: 500) {
                try await LeancloudManager.instance.save(todo: voiceBean)
            }
            //更新AiVoiceCrowdBean
            try await retry(maxRetries: 5, retryDelayMillis: 500) {
                bean.count = (bean.count ?? 0) + 1
                try await LeancloudManager.instance.save(todo: bean)
            }
            //扣除次数
            if (deduct) {
                var aiVoiceClone = userManager.getExtraConfig().aiVoiceClone ?? 0
                aiVoiceClone -= 1
                userManager.getExtraConfig().aiVoiceClone = aiVoiceClone
                try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    if let user = userManager.user {
                        try await LeancloudManager.instance.save(todo: user)
                        userManager.update()
                    }
                }
            }
            return true
        } suc: { _ in
            showToast("购买成功")
            NotificationCenter.default.post(name: .buyVoice, object: true)
        } fail: {_ in
            showTipsDialog(text: "购买失败") {}
        }
        
    }
    
    func doJoin(crowdBean: AiVoiceCrowdBean, price:Double) {
        
        request {
            try check(userManager.isLogin(), "请先登陆")
            crowdBean.price = crowdBean.price + price
            try await retry(maxRetries: 5, retryDelayMillis: 500) {
                try await LeancloudManager.instance.save(todo: crowdBean)
            }
            //先查询是否存在
            let query = LCQuery(className: "AiVoiceCrowdData")
            query.whereKey("crowdId", .equalTo(crowdBean.objectId ?? ""))
            query.whereKey("userId", .equalTo(userManager.getUserId()))
            var crowdDataBean = try await retry(maxRetries: 5, retryDelayMillis: 500) {
                try await LeancloudManager.instance.getFirst(query: query, modeType: AiVoiceCrowdDataBean.self)
            }
            if crowdDataBean == nil {
                crowdDataBean = AiVoiceCrowdDataBean()
                crowdDataBean?.crowdId = crowdBean.objectId
                crowdDataBean?.userId = userManager.getUserId()
                crowdDataBean?.price = 0.0
            }
            crowdDataBean?.price = (crowdDataBean?.price ?? 0) + price
            //更新AiVoiceCrowdBean
            try await retry(maxRetries: 5, retryDelayMillis: 500) {
                try await LeancloudManager.instance.save(todo: crowdDataBean!)
            }
            //音色开始上传到自己的账号
            //查询是否已经存在了，避免重复添加
            let query2 = LCQuery(className: "AiVoice")
            query2.whereKey("crowdId", .equalTo(crowdBean.objectId ?? ""))
            query2.whereKey("userId", .equalTo(userManager.getUserId()))
            let voiceBean = try await LeancloudManager.instance.getFirst(query: query2, modeType: AiVoiceBean.self)
            if voiceBean != nil {
                showLog("已经存在了，不需要添加")
            } else {
                let voiceBean = AiVoiceBean()
                voiceBean.name =  crowdBean.name
                voiceBean.userId = userManager.getUserId()
                voiceBean.crowdId = crowdBean.objectId
                try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    try await LeancloudManager.instance.save(todo: voiceBean)
                }
            }
            return true
        } suc: { _ in
            showToast("参与成功")
            NotificationCenter.default.post(name: .buyVoice, object: true)
        } fail: {it in
            showTipsDialog(text: it.message) {}
        }
        
    }
    
    deinit {
        AudioPlayerManager.shared.pause()
    }
}
